package com.huhao.wshare.service.impl;

import com.huhao.wshare.dto.AjaxResult;
import com.huhao.wshare.service.EmailService;
import com.huhao.wshare.service.VerifyCodeService;
import com.huhao.wshare.service.constant.VerificationCodeType; // 新增导入
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class VerifyCodeServiceImpl implements VerifyCodeService {

    @Autowired
    private EmailService emailService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private ResourceLoader resourceLoader;

    // private static final String VERIFY_CODE_PREFIX = "register_verify_code:"; // 已被枚举替代
    private static final int EXPIRE_TIME = 5; // 验证码有效期 5 分钟

    @Override
    public AjaxResult<String> sendVerificationCode(String email, VerificationCodeType type) { // 修改方法签名
        String emailRegex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
        if (!Pattern.matches(emailRegex, email)) {
            return AjaxResult.fail("无效的邮箱地址");
        }

        String verificationCode = generateVerificationCode();
        String emailContent = loadEmailTemplate(verificationCode);

        try {
            // 使用枚举中的邮件主题
            emailService.sendEmail(email, type.getEmailSubject(), emailContent);
        } catch (Exception e) {
            return AjaxResult.fail("邮件发送失败");
        }

        // 使用枚举中的 Redis Key 前缀
        redisTemplate.opsForValue().set(type.getRedisPrefix() + email, verificationCode, EXPIRE_TIME, TimeUnit.MINUTES);

        return AjaxResult.success("验证码发送成功");
    }

    @Override
    public boolean verifyCode(String email, String code, VerificationCodeType type) { // 修改方法签名
        String redisKey = type.getRedisPrefix() + email; // 使用枚举中的 Redis Key 前缀
        String storedCode = redisTemplate.opsForValue().get(redisKey);
        if (storedCode != null && storedCode.equals(code)) {
            // 验证成功后删除验证码
            redisTemplate.delete(redisKey);
            return true;
        }
        return false;
    }

    private String generateVerificationCode() {
        return String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
    }

    private String loadEmailTemplate(String code) {
        try {
            Resource resource = resourceLoader.getResource("classpath:templates/email.html");
            String template = new BufferedReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))
                    .lines()
                    .collect(Collectors.joining(System.lineSeparator()));
            return template.replace("{{code}}", code);
        } catch (Exception e) {
            throw new RuntimeException("加载邮件模板失败", e);
        }
    }
}
